package com.jaws.core.mvc.token;

import java.util.List;
import java.util.UUID;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;

import com.google.common.base.Splitter;
import com.google.common.collect.Lists;
import com.jaws.core.common.vo.OpResponse;

/**
 * 防页面重复提交token管理类，接redis待续
 * @author maojian
 * @date 2017-05-11 09:41:08
 * @since v1.0.0
 */
public class TokenManager {

	public final static String TOKEN = "formToken";

	/**
	 * 放到缓存中的token的key的前缀
	 */
	private final String TOKEN_PREFIX = "token_";

	/**
	 * token
	 */
	private static final String TOKEN_STR = "token";
	/**
	 * 默认过期时间
	 */
	private final int DEFAULT_EXPIRE = 180;

	/**
	 * 插入时候默认的重试次数
	 */
	private final int DEFAULT_RETRY_TIMES = 3;

	/**
	 * 放到缓存中的token的过期时间
	 */
	private int expire = DEFAULT_EXPIRE;

	/**
	 * token放到缓存中的重试次数
	 */
	private int retryTimes = DEFAULT_RETRY_TIMES;

	/**
	 * 正确的返回码的list
	 */
	private List<String> sucCodeList;

	/**
	 * 缓存客户端
	 */
	// private MemCachedClient client;

	public String newToken() {
		String token = null;
		// 这里分配token的时候,如果分配失败(重复或者网络问题等)的话,默认重试3次，如果失败服务降级随机生成一个
		for (int i = 0; i < retryTimes; i++) {
			if (token != null) {
				break;
			}
			token = UUID.randomUUID().toString();
			// boolean suc = client.add(TOKEN_PREFIX + token, TOKEN_STR, expire);
			boolean suc = true;
			if (!suc) {
				token = getToken(token);
			}
		}
		if (null == token) {
			token = UUID.randomUUID().toString();
		}
		return token;
	}

	public boolean checkToken(String token) {
		// Object realToken = client.get(TOKEN_PREFIX + token);
		// return realToken == null ? false : realToken.equals(TOKEN_STR);
		return false;
	}

	public String getToken(String token) {
		// return null == client.get(TOKEN_PREFIX + token) ? null : (String)client.get(TOKEN_PREFIX + token);
		return null;
	}

	public boolean checkAndDelToken(String token) {
		if (checkToken(token)) {
			// return client.delete(TOKEN_PREFIX + token);
		}
		return false;
	}

	@Value("#{globalProp[sucCodeList]}")
	public void setSucCodeList(String sucCodeList) {
		if (StringUtils.isBlank(sucCodeList)) {
			this.sucCodeList = Lists.newArrayList(String.valueOf(OpResponse.SUCCESS_CODE));
		} else {
			this.sucCodeList = Lists.newArrayList(Splitter.on(",").split(sucCodeList));
		}
	}

	public List<String> getSucCodeList() {
		return sucCodeList;
	}

	// public MemCachedClient getClient() {
	// return client;
	// }
	//
	// public void setClient(MemCachedClient client) {
	// this.client = client;
	// }

}
